#include<iostream>
#include"socket.hpp"
#include<sys/select.h>
#include<vector>
uint16_t defaulrport=8080;
const int count=sizeof(fd_set)*8;
int defaultdata=-1;
class selectserver
{
public:

selectserver(uint16_t port=defaulrport)
:_port(port)
{
   for(int i=0;i<count;i++)
    {
      num[i]=defaultdata;

    }


}
void init()
{
 _listensock.Socket();
 _listensock.Bind(_port);
 _listensock.Listen();
 
}
void start()
{
  num[0]=_listensock.fd();
  int maxfd=num[0];
  for( ;;)
  {
     fd_set st;
     FD_ZERO(&st);
    for(int i=0;i<count;i++)
    {
       if(num[i]==defaultdata)
       continue;
       maxfd=max(maxfd,num[i]);
       FD_SET(num[i],&st);

    }

    int n=select(maxfd+1,&st,nullptr,nullptr,nullptr);
    if(n==0)
    {
       cout<<"time out..."<<endl;
   
    }
    else if(n<0)
    {

      cout<<"select error..."<<endl;
  

    }
    else
    {

     cout<<"select succeed..."<<endl;
     deal(st);



    }





  }


}
void deal(fd_set&st)
{

  for(int i=0;i<count;i++)
  {
    if(num[i]==defaultdata)
    continue;
    else
    {
    int fd=num[i];
    if(FD_ISSET(fd,&st))
    {
     if(fd==_listensock.fd())
     {
       
     accepter();


     }
     else
     {

     reader(fd,i);

     }

    }

      
    }

  }


}
void accepter()
{

  uint16_t clientport;
  string  clientip;

int sock= _listensock.Accept(&clientport,&clientip);
if(sock<0)
{
cout<<"accept error ..."<<endl;

}
cout<<"clentport:"<<clientport<<" "<<"clentip:"<<clientip;

int pos=1;
for( ;pos<count;pos++)
  {
   if(num[pos]==defaultdata)
   break;
  }

  if(pos!=count)
  {
    num[pos]=sock;

  }
  else
  { 
    cout<<"no position..."<<endl;
    close(sock);



  }






}
void reader(int fd,int pos)
{
  char buffer[1024];
  int n=read(fd,buffer,sizeof(buffer));
  if(n==0)
  {
    num[pos]=defaultdata;
    close(fd);


  }
  else if(n<0)
  {
     num[pos]=defaultdata;
    close(fd);




  }
  else
  {

   buffer[n]=0;
   cout<<buffer<<endl;



  }






}

private:
sock _listensock;
uint16_t _port;
int num[count];

};
